package net.javaw.callplatform;

import net.javaw.callplatform.util.DialogUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Setting extends Activity {

	// 定义界面中一个文本框
	EditText Ecaller;
	// 定义界面中两个按钮
	Button Bsave, Bcancel;
	
	SharedPreferences preferences;
	SharedPreferences.Editor editor;
	
	@SuppressLint("WorldReadableFiles")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting);
		
		// 获取只能被本应用程序读、写的SharedPreferences对象
		preferences = getSharedPreferences("net.javaw.callplatform", MODE_WORLD_READABLE);
		editor = preferences.edit();
		
		Ecaller = (EditText) findViewById(R.id.caller);
		
		if(null!=preferences.getString("caller", null))
		{
			Ecaller.setText(preferences.getString("caller", null));
		}
		
		Bsave = (Button) findViewById(R.id.save);
		Bsave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				String caller = Ecaller.getText().toString();
				
				if(validateCaller(caller))
				{
					// 删除旧的本机号码
					editor.remove("caller");
					// 存入本机号码
					editor.putString("caller", caller);
					// 提交所有存入的数据
					editor.commit();
					
					Toast.makeText(getApplicationContext(), "本机号码保存成功！", Toast.LENGTH_SHORT).show();
					
					// 启动Main Activity
					Intent intent = new Intent(Setting.this, Notifications.class);
					startActivity(intent);
					// 结束该Activity
					finish();
					
				}else
				{
					Toast.makeText(getApplicationContext(), "本机号码保存失败，请重新保存！", Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Toast.makeText(getApplicationContext(), "待扩展。。。\n\n河南卓辉通信技术有限公司版权所有\n\n免责声明\n\n河南卓辉通信版权所有\n\n作者：史守阳\n\n仅限河南卓辉通信内部员工使用", Toast.LENGTH_LONG).show();
		return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) 
		{
			// 启动Main Activity
			Intent intent = new Intent(Setting.this, Notifications.class);
			startActivity(intent);
			// 结束该Activity
			finish();
		}else if(keyCode == KeyEvent.KEYCODE_MENU) 
		{
			Toast.makeText(getApplicationContext(), "设置本机号码\n\n步骤：\n\n1、选择菜单键，进入本机号码设置界面\n\n2、输入本机号码，保存", Toast.LENGTH_LONG).show();
		}
		return true;
	}
	
	// 对用户输入的用户名、密码进行校验
	private boolean validateCaller(String caller)
	{
		if ("".equals(caller))
		{
			DialogUtil.showDialog(this, "本机号码不能为空！", false);
			return false;
		}
		return true;
	}

}
